package com.cqrt.aop;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.cqrt.config.CustomObjectMapper;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.mapper.RTTaskMapper;
import com.cqrt.mapper.RtWorkItemMapper;
import com.cqrt.vo.CheckDeliversErrorVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchTypeDTO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.core.response.TyppmResponseResult;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.rpm.controller.meta.EnumController;
import com.hustcad.plm.rpm.model.dto.job.JobStatusUpdateDTO;
import com.hustcad.plm.rpm.model.dto.job.TyppmJobDTO;
import com.hustcad.plm.rpm.model.dto.outrule.TyppmOutRuleDTO;
import com.hustcad.plm.rpm.model.dto.plan.CheckDeliversError;
import com.hustcad.plm.rpm.model.dto.remote.BatchInsertDocVO;
import com.hustcad.plm.rpm.model.dto.remote.DocDetailsVO;
import com.hustcad.plm.rpm.model.dto.remote.RemoteObjDTO;
import com.hustcad.plm.rpm.model.entity.job.TyppmJob;
import com.hustcad.plm.rpm.model.entity.outrule.TyppmOutRule;
import com.hustcad.plm.rpm.model.vo.meta.EnumerationItemTreeVO;
import com.hustcad.plm.rpm.model.vo.recent.TyppmOperationRecordVO;
import com.hustcad.plm.rpm.service.job.TyppmJobService;
import com.hustcad.plm.rpm.service.meta.TyppmEnumerationDefService;
import com.hustcad.plm.rpm.service.outrule.TyppmOutRuleService;
import com.hustcad.plm.rpm.service.remote.TyppmRemotePdmService;
import com.hustcad.plm.rpm.service.remoterequest.ThirdRemoteRequestService;
import com.hustcad.plm.rpm.util.request.RequestBase;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.vo.AttributeVO;
import com.ty.ppm.model.entity.job.Job;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class TaskAop {


    @Resource
    private RTTaskMapper rtTaskMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyppmRemotePdmService typpmRemotePdmService;
    @Resource
    private TyppmOutRuleService typpmOutRuleService;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private TyppmJobService typpmJobService;
    @Resource
    private RtWorkItemMapper rtWorkItemMapper;



    @Value("${query.url}")
    private String queryConditionUrl;
    @Resource
    private TyppmEnumerationDefService typpmEnumerationDefService;

    @Around("execution(* com.hustcad.plm.rpm.service.job.TyppmJobService.getJobCanSubmitByOID(..))")
    public Object aroundControllerMethods(ProceedingJoinPoint joinPoint) throws Throwable {
        List<CheckDeliversError> arr =(List<CheckDeliversError>)joinPoint.proceed();

        String jobId = (String) joinPoint.getArgs()[0];
        List<TyppmOutRuleDTO> outRuleDTOS = typpmOutRuleService.queryOutRuleByPage(jobId, null, 1, 9999).getList();
        List<String> temporaryJobOidList =rtTaskMapper.selectTemporaryJobOid(jobId);
        Map<String, TyppmOutRuleDTO> temporaryJobOutRuleMap = new HashMap<>();
        if(CollUtil.isNotEmpty(temporaryJobOidList)){
            for (String temporaryJobOid : temporaryJobOidList) {
                List<TyppmOutRuleDTO> temporaryJobOutRuleList = typpmOutRuleService.queryOutRuleByPage(temporaryJobOid, null, 1, 9999).getList();
                if(CollUtil.isEmpty(temporaryJobOutRuleList)){
                    continue;
                }
                for (TyppmOutRuleDTO typpmOutRuleDTO : temporaryJobOutRuleList) {
                    temporaryJobOutRuleMap.put(typpmOutRuleDTO.getName(),typpmOutRuleDTO);
                }
            }
        }
        List<EnumerationItemTreeVO> outRuleTypeTree = this.typpmEnumerationDefService.queryEnumerationTree("Out Rule");
        if(CollUtil.isNotEmpty(arr)){
            List<CheckDeliversErrorVO> list = BeanUtil.copyToList(arr, CheckDeliversErrorVO.class);
            for (CheckDeliversErrorVO checkDeliversError : list) {
                Optional<TyppmOutRuleDTO> t = outRuleDTOS.stream().filter(
                        f -> f.getName().equals(checkDeliversError.getRuleName())).findFirst();
                if (t.isPresent()) {
                    TyppmOutRuleDTO typpmOutRuleDTO = t.get();
                    checkDeliversError.setRuleContent(typpmOutRuleDTO.getRuleDisplayName());
                    String parentRuleTypeOid = getParentRuleTypeOid(typpmOutRuleDTO.getRuletypeOid(),outRuleTypeTree);
                    checkDeliversError.setParentOutRuleType(parentRuleTypeOid);
                    if(CollUtil.isNotEmpty(temporaryJobOutRuleMap)){
                        if(temporaryJobOutRuleMap.containsKey(typpmOutRuleDTO.getName())){
                            checkDeliversError.setIsExistTemporaryJob("是");
                        }else {
                            checkDeliversError.setIsExistTemporaryJob("否");
                        }
                    }
                }
            }
            return list;
        }
        return arr;
    }

    private String getParentRuleTypeOid(String ruleTypeOid, List<EnumerationItemTreeVO> outRuleTypeTree) {
        for (EnumerationItemTreeVO enumerationItemTreeVO : outRuleTypeTree) {
            if (enumerationItemTreeVO.getId().equals(ruleTypeOid)) {
                return enumerationItemTreeVO.getPid();
            } else {
                String parentRuleTypeOid = getParentRuleTypeOid(ruleTypeOid, enumerationItemTreeVO.getChildren());
                if (parentRuleTypeOid != null) {
                    return parentRuleTypeOid;
                }
            }
        }
        return null;
    }

    @Around("execution(* com.cqrt.service.RTTaskService.batchImportTask(..))")
    public Object theProjectHasResumedAndStarted(ProceedingJoinPoint joinPoint) throws Throwable {

        List<TyppmJobDTO> jobDTOList = (List<TyppmJobDTO>) joinPoint.proceed();
        if (CollUtil.isNotEmpty(jobDTOList)){
            rtTaskMapper.updateJobState(jobDTOList);
        }
        return jobDTOList;
    }


}


